package cn.fz.mpdemo.service.impl;

import cn.fz.mpdemo.domain.vo.BusinessDataVO;
import cn.fz.mpdemo.exception.BizException;
import cn.fz.mpdemo.service.ReportService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.time.LocalDate;

@Service
public class ReportServiceImpl implements ReportService {
    /**
     * 导出近30天的运营数据报表
     * @param response HttpServletResponse
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        // 查询概览运营数据，提供给Excel模板文件
        BusinessDataVO dataVO = BusinessDataVO.builder()
                .orderCompletionRate(99.95)
                .turnover(200000.0)
                .unitPrice(888.99)
                .validOrderCount(600)
                .newUsers(200)
                .build();
        String tempPath = "template/运营数据报表模板.xlsx";
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(tempPath);
        try{
            //基于提供好的模板文件创建一个新的Excel表格对象
            assert inputStream != null;
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(dataVO.getTurnover());
            row.getCell(4).setCellValue(dataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(dataVO.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(dataVO.getValidOrderCount());
            row.getCell(4).setCellValue(dataVO.getUnitPrice());

            // 通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();

            out.close();
            excel.close();
        }catch (Exception e){
            throw new BizException(e.getMessage());
        }
    }
}
